/*******************************************************************************
*  Project      : Minigate Golfin                                 
*  Program ID   : home.js                                 
*  Description  : 클럽개별메인 
*
********************************************************************************
*  Program History                                                            
*  Date        Author    Description                                          
*  ----------  --------  -------------------------------------------------------- 
*  2012-06-12  이윤노    Created.  
*  2012-06-14  이윤노    Complete.  
*******************************************************************************/

jQuery(function($){
	
	//전체게시판/내가쓴글 
	function clsClubBoardTitle(){
		this._HTMLDom = null;
		this._init();		
	}
	
	clsClubBoardTitle.prototype = {
		_init: function(){
			var $layer = $("div#container section#main_content article.depth2_tab");
			
			this._HTMLDom = {
				"$layer": $layer
				,"$tabs": $layer.find("li")
			};
			
			$layer.data("idx", null); // 인덱스로 관리
			this.display();
		}
		, $getBtnTab: function(){
			var $layer = this._HTMLDom["$layer"];
			var $tabs = this._HTMLDom["$tabs"];
			
			return $tabs.find("a");
		}
		, display: function(){
			var $layer = this._HTMLDom["$layer"], $tabs = this._HTMLDom["$tabs"];
			var idx = $layer.data("idx");
			
			// 현재 인덱싱된 타이틀만 on설정
			$tabs.find("img").each(function(n){
				var imgSrc = $(this).attr("src");
				var szImgName = imgSrc.replace(/(.*)\/(.*).gif/g, function(){
					return arguments[1] + "/" + arguments[2].replace("_on", "");
				});
				
				$(this).attr("src", szImgName + ((idx == n) ? "_on":"") + ".gif");				
			});			
			
		}
		, setIdx: function(val){
			var $layer = this._HTMLDom["$layer"];			
			if(val == $layer.data("idx")) return false;			
			$layer.data("idx", val);			
			this.display();
			return true;
		}					
	}
	
	// 검색타입
	function clsSearchType()
	{
		this._HTMLDom = null;
		this.idx = null;
		
		this._init();
	}
	
	clsSearchType.prototype = {
		_init: function(){
			var $layer = $("div#container section#main_content div.golf_board article.golf_board_search div.selectlayer");
			
			this._HTMLDom = {
				"$layer": $layer
			}
			$layer.find("li:eq(1)").remove();
			this.idx = 0;			
			this._bind();
		}
		, _bind: function(){
			var thisClass = this;
			var $layer = this._HTMLDom["$layer"];
			
			$layer.find("p:eq(0)").click(function(event){
				event.preventDefault();
				
				if($layer.find("ul").css("display")=="block") $layer.find("ul").hide(300);
				else $layer.find("ul").show(300);
			});
			
			$layer.find("li a").click(function(event){
				event.preventDefault();
				
				thisClass.setIdx($layer.find("li a").index($(this)));
			});
		}
		, display: function(){
			var $layer = this._HTMLDom["$layer"];
			
			$layer.find("p:eq(0) a").html($layer.find("li a").eq(this.idx).html());
		}
		, setIdx: function(idx){
			this.idx = idx;
			this.display();
			this._HTMLDom["$layer"].find("ul").hide(300);
		}
		, $getSelect: function(){
			return this._HTMLDom["$layer"].find("ul");
		}
		, getValue: function(){
			return this.idx;
		}
	}
	
	// 검색어
	function clsSearchText()
	{
		this._HTMLDom = null;
		this._ERRMSG = {
			"_NOVALUE": "검색어를 입력해 주십시요."
		}
		this.errMsg = null;
		
		this._init();
	}
	
	clsSearchText.prototype = {
		_init: function(){
			var $layer = $("div#container section#main_content div.golf_board article.golf_board_search :text");
			this._HTMLDom = {
				"$layer": $layer
			}
		}
		, getValue: function(){
			return this._HTMLDom["$layer"].val();
		}
		, isValid: function(){
			this.errMsg = null;
			
			if(this.getValue() == ""){
				this.errMsg = this._ERRMSG["_NOVALUE"];
				return false;
			}
			
			return true;
		}
		, getError: function(){
			return this.errMsg;
		}
		, focus: function(){
			this._HTMLDom["$layer"].trigger("focus");
		}
	}
	
	//게시판목록
	function clsClubAlbumList(){
		this._HTMLDom = null;
		this.boardList = null;
		this.clubInfoData = null;
		this._init();
	}
	
	clsClubAlbumList.prototype = {
		_init: function(){
			var $layer = $("div#container article.pic_list");
			this._HTMLDom = {
				"$layer": $layer
				, "$element": $layer.find("li:first")
				, "$empty": $("article.board_list_none").html("등록된 글이 없습니다.").hide()
			}
			
			$layer.find("ul").empty();
		}
		, setList: function(thisData){
			this.boardList = thisData;
			this.display();
		}
		, addProfile: function(n, thisData){
			this.boardList[n]["프로필"] = thisData;
		}
		, display: function(){
			var $layer = this._HTMLDom["$layer"].find("ul");
			var $element = this._HTMLDom["$element"];
			var thisClass = this;
			
			$layer.empty();
			
			if(!this.boardList.length){				
				this._HTMLDom["$empty"].show();
				$("#idClubAlbumListPage").hide();
				$("article.btn_area").hide();
			}else{
				this._HTMLDom["$empty"].hide();
				$("#idClubAlbumListPage").show();
				$("article.btn_area").show();
			}
						
			for(var i=0;i<this.boardList.length;++i){
				$layer.append($element.clone(true));
			}
			
			$layer.find("li").eq(4).addClass("last");
			$layer.find("li").eq(9).addClass("last");

			$layer.find("li").each(function(n){				
				$(this).find("img:eq(0)").attr("src",_gf.filePath2Url(thisClass.boardList[n]["게시판이미지"])).click(function(event){					
					document.objControl.goView(n);
				}).width(154).height(115);
				$(this).find("a em").contents().filter(function(){
					return (this.nodeType==3&&this.data.trim());
				}).after(_util.leftB(thisClass.boardList[n]["제목"],45)).remove();
				$(this).find("a em").click(function(event){					
					document.objControl.goView(n);
				});
				$(this).find("a em span").html((thisClass.boardList[n]["댓글수"] != "0")?"(" + getFormatNumber(thisClass.boardList[n]["댓글수"]) + ")":"");
				$(this).find("p.date").contents().filter(function(){
					return (this.nodeType==3&&this.data.trim());
				}).after(getFormatDateYmd(thisClass.boardList[n]["작성일"],"-")).remove();
				
				$tmp = $(this).find("p.date span.nice").children().clone(true);
				$(this).find("p.date span.nice").html("나이스샷("+ getFormatNumber(thisClass.boardList[n]["나이스샷"])+")").prepend($tmp);
			
				$(this).find("p.name").html(thisClass.boardList[n]["작성자"]["닉네임"]).hover(function(event){
					_gf.showProfileLayer($(this), thisClass.boardList[n]["프로필"], "left", 0, 13);
				}, function(event){
					_gf.closeProfileLayer();
				});				
			});
		}
		, spinStart: function(){
			var $layer = this._HTMLDom["$layer"];
			
			$layer.parent().hide();
			if($layer.parent().prev("div#tmpSpin").length == 0){ 
				$layer.parent().before("<div id='tmpSpin' style='width:950px; height:100px;'></div>");
			}
			$layer.parent().prev("div#tmpSpin").show().spin();
		}
		, spinEnd: function(){
			var $layer = this._HTMLDom["$layer"];			
			$layer.parent().prev("div#tmpSpin").spin(false).hide();
			$layer.parent().show();
		}
		, $getBtnChecked: function(){			
			return this._HTMLDom["$layer"].find("input:checkbox:checked");	
		}
		, $getBtnCheckbox: function(){			
			return this._HTMLDom["$layer"].find("input:checkbox");	
		}
		, getArrChecked: function(){
			var aRet = [];
			
			this._HTMLDom["$layer"].find("input:checkbox").each(function(n){
				if($(this).is(":checked")) aRet.put(n)
			});
		}
		, getClickData: function(){
			return this._HTMLDom["$layer"].find("tr td:eq(2) a");
		}
		, $getBtnWrite: function(){			
			return $("div#container section#main_content div.golf_board article.depth2_tab p.btn_depth a")	;
		}		
	}	
	
	function clsComm()
	{
		this.clubAlbumList = null;
		this.clubAlbumListPageData = null;
		this.clubAlbumListRequest = null;		
		
		this._init();
	}
	
	clsComm.prototype = {
		_init: function(){
		
			this.clubAlbumListRequest = {
				 "동호회키":null
				, "페이지": null
				, "내글": null					
				, "검색종류":null
				, "검색어":null
			}
			
			this.clubAlbumListPageData = {
				"전체수": null	
			}
		}
//------------------------ 게시판글목록------------------------//		
		, getClubAlbumList: function(){
			var thisClass = this;
			
			szAll = "";
			szContent = "";
			szNickName = "";	
			
			szClubSeq = this.clubAlbumListRequest["동호회키"];
			szServicename = (this.clubAlbumListRequest["내글"]?"getClubBoardMyList": "getClubBoardList");		
			szPage = this.clubAlbumListRequest["페이지"];
			szText = this.clubAlbumListRequest["검색어"];
			
			switch(this.clubAlbumListRequest["검색종류"]){
				case 0:  szAll = szText; break; //전체
				case 1:  szContent =  szText; break;//제목+내용
				case 2:  szNickName	= szText; break;//작성자
				default : break;
			}
			
			// ajax 시작
			//parameter setting and run
			_gf.ajax({
				"sid":"CB001",
				"servicename": szServicename,
				"listcount":10,
				"currpageno":szPage
			}, {
				"club_seq": szClubSeq
				, "board_type": "P"
				, "title": ""
				, "content": szContent				
				, "reg_nickname": szNickName
				, "search": szAll				
			}, function(ret){
							
				// callback and mapping
				thisClass.clubAlbumList = [];
				
				thisClass.clubAlbumListPageData = {
					"전체수": ret["msp"]["contents"]["@totalcount"]
				}
					
				if(ret["msp"]["contents"]["items"]){					
					if(!ret["msp"]["contents"]["items"].length){
						ret["msp"]["contents"]["items"]	= new Array(ret["msp"]["contents"]["items"]);
					}					
					for(var i=0;i<ret["msp"]["contents"]["items"].length;i++){						
						var obj = 	ret["msp"]["contents"]["items"][i];
						thisClass.clubAlbumList.push({
						"삭제권한": _util.nvl(obj["my__article__yn"])
						, "동호회키": _util.nvl(obj["club__seq"])
						, "게시판키": _util.nvl(obj["board__seq"])
						, "제목": _util.nvl(obj["title"])
						, "댓글수": _util.nvl(obj["cr__cnt"])
						, "작성자": {
												  "이미지": _util.nvl(obj["user__image"])
												, "닉네임": _util.nvl(obj["reg__nickname"])
												, "아이디": _util.nvl(obj["reg__id"])
												}
						, "작성일":   _util.nvl(obj["reg__date"])
						, "작성시간":   _util.nvl(obj["reg__time"])
						, "조회수": _util.nvl(obj["hit"])
						, "나이스샷": _util.nvl(obj["niceshot"])
						, "공개유무": _util.nvl(obj["view__type"])
						, "게시판이미지": _util.nvl(obj["filepath"])
						, "프로필": []
						});						
					}
				}
				
				$(thisClass).trigger("evtFinishClubAlbumList" );
			});
			// ajax 끝
		}
		, getClubAlbumListData: function(){
			return this.clubAlbumList;
		}
		, getClubAlbumListPageData: function(){
			return this.clubAlbumListPageData;
		}
		, setClubAlbumListRequest: function(key, val){
			this.clubAlbumListRequest[key] = val;
		}
		, getClubAlbumListRequest: function(key){
			return this.clubAlbumListRequest[key];
		}	
//------------------------ 게시판글목록------------------------//	
//------------------------ 게시판글삭제------------------------//				
		, deleteClubAlbumList: function(arg){			
			var thisClass = this;
			var board_seq = arg["게시판키"];
			
			// ajax 시작
			//parameter setting and run
			_gf.ajax({
				"sid":"CB001",
				"servicename":"deleteClubBoard"
			}, {
				"board_seq": board_seq					
			}, function(ret){
				
				// callback and mapping				
				var resData = {
					"응답코드": (ret["msp"]["contents"]["serviceResult"]=="00000"?true:false)
					, "메세지": _gf.getResultMsg(ret)
				};
				
				$(thisClass).trigger("evtFinishClubDelete", [resData]);
			});
			// ajax 끝
			
		}
//------------------------ 게시판글삭제------------------------//			
	}
	
	function clsControl()
	{
		this.objComm = null;
		
		this.objClubInfo = null
		this.objRole = null;
		
		this.objClubBoardTitle = null;
		this.objSearchType = null;
		this.objSearchText = null;
		
		this.objClubAlbumList = null;
		this.objClubAlbumListPage = null;
		
		this.club_seq = null;
		this.club_my = null;
	}
	
	clsControl.prototype = {
		_init: function(){
			var member_id = _util.getCookie("member_id");
			this.club_seq = _util.getParam("club_seq");
			this.club_my = (_util.getParam("club_my") == "Y") ? 1:0;
			
			if(!this.club_seq) document.location.href = "../club/club.html";
			
			if(!member_id) {
				/*if(confirm("로그인 후 이용하여 주세요.")){
					_gf.goLogin();						
				}else{
					document.location.href = "../club/club.html";
				}				*/
			}else if(!this.club_seq) {
				document.location.href = "../club/club.html";
			}
			
			this._preload();
			
			this.objComm = new clsComm();
			this.objClubBoardTitle = new clsClubBoardTitle();
			this.objSearchType = new clsSearchType();
			this.objSearchText = new clsSearchText();		
			this.objClubAlbumList = new clsClubAlbumList();				
			this.objClubAlbumListPage = new _gf.makePaging($("#idClubAlbumListPage"), 10, 10);
			
			this._beforeStart();
			this._bind();
		}
		, _preload: function(){
			_gf.spinStart();
		}
		, _beforeStart: function(){
			var thisClass = this;
			this._permitStart = {
				
			}
			
			$.ajax({
				url: "js/self_club_top.js"
				, dataType: "script"
				, async: false
				, success: function(){
					
				}
				, error: function(){
					alert("error");
				}
			});
			
			_util.executeThread(function(){
				for(var k in thisClass._permitStart){
					if(!thisClass._permitStart[k]) return false;
				}
				
				return (_clubControl.getClubInfo().infoData);
			}, function(){				
				_gf.spinEnd();;
				thisClass._start();
			});	
		}
		, _role: function(){
			if(!this.objRole.isAdmin()){//0-일반회원, 1-매니저/개설자
				//글삭제
				$("div.golf_board  article.btn_area a").hide();
				$("input:checkbox").hide();
			}
		}
		, _start: function(){		
			this.objClubInfo = _clubControl.getClubInfo();
			this.objRole = new clsRole(this.objClubInfo.infoData);
			this._role();
			
			//전체글(0),내가쓴글(1) 인덱스설정 및 검색조건 
			this.objClubBoardTitle.setIdx(this.club_my);			
			
			//게시판글목록 조회				
			this.objClubAlbumList.spinStart();
			this.objComm.setClubAlbumListRequest("동호회키",this.club_seq);
			this.objComm.setClubAlbumListRequest("내글",this.club_my);
			this.objComm.setClubAlbumListRequest("페이지",1);
			this.objComm.setClubAlbumListRequest("검색종류",0);
			this.objComm.setClubAlbumListRequest("검색어","");								
			this.objComm.getClubAlbumList();
			this.objClubAlbumListPage.setPage(1);
		}
		, _bind: function(){
			var thisClass = this;
			
			//동호회 글목록조회  완료 이벤트 
			$(this.objComm).bind("evtFinishClubAlbumList", function(){
				var thisData = thisClass.objComm.getClubAlbumListData()
				var pageData = thisClass.objComm.getClubAlbumListPageData();
				
				thisClass.objClubAlbumList.spinEnd();
				thisClass.objClubAlbumList.setList(thisData);
				
				// 페이지 부에 전체 수설정 				
				thisClass.objClubAlbumListPage.setTotalCount(pageData["전체수"]);
				thisClass.objClubAlbumListPage.display();
				
				//프로필
				for(var i=0;i<thisData.length;++i){					
					_gf.getMemberInfo({
						"아이디": thisData[i]["작성자"]["아이디"]
						, "인덱스": i
						, "콜백": function(res, info, arg){
							thisClass.objClubAlbumList.addProfile(arg["인덱스"], info);
						}
					});
				}
			});
			
			// 페이지이동 이벤트
			$(this.objClubAlbumListPage).bind("evtPageClick", function(){
				var thisPage = this.getPage();
				
				thisClass.objComm.setClubAlbumListRequest("페이지", thisPage);
				thisClass.objClubAlbumList.spinStart();
				thisClass.objComm.getClubAlbumList();
			});
			
			// 삭제완료 이벤트
			$(this.objComm).bind("evtFinishClubDelete", function(event, resData){				
				alert(resData["메세지"]);				
				
				if(resData["응답코드"]) {					
					var thisPage = thisClass.objClubAlbumListPage.getPage();				
					thisClass.objComm.setClubAlbumListRequest("페이지", thisPage);
					thisClass.objClubAlbumList.spinStart();
					thisClass.objComm.getClubAlbumList();					
				}
			});
			
			//전체글/내글
			this.objClubBoardTitle.$getBtnTab().click(function(){
				var idx = thisClass.objClubBoardTitle.$getBtnTab().index($(this));
				
				if(!thisClass.objRole.isMember() && idx==1){
					alert(thisClass.objRole.getError());
					return;
				}						
				document.location.href = document.location.pathname + "?club_seq=" + thisClass.club_seq + (idx? "&club_my=Y":"");
			});
			
			//상세보기
			$(this.objClubAlbumList).bind("clubView",function(event, n){
				event.preventDefault();					
				if(!thisClass.objRole.isOpenView(thisClass.objClubAlbumList.boardList[n]["공개유무"])){
					alert(thisClass.objRole.getError());
					return;
				}
				document.location.href = "club_picture_view.html?club_seq=" + thisClass.club_seq + "&board_seq="+ thisClass.objClubAlbumList.boardList[n]["게시판키"] + "&club_my=" +(thisClass.club_my? "&club_my=Y":"");
			});
			
			//글쓰기 이동
			this.objClubAlbumList.$getBtnWrite().click(function(event){
				event.preventDefault();	
				if(!thisClass.objRole.isMember()){
					alert(thisClass.objRole.getError());
					return;
				}		
				document.location.href = "club_picture_write.html?club_seq=" + thisClass.club_seq;
			});
			
			// 검색 이벤트
			$("article.golf_board_search :image").click(function(event){
				event.preventDefault();
				
				if(!thisClass.objSearchText.isValid() & thisClass.objSearchType.getValue() != 0){
					alert(thisClass.objSearchText.getError());
					thisClass.objSearchText.focus();
					return;
				}				
				
				thisClass.objComm.setClubAlbumListRequest("검색종류", thisClass.objSearchType.getValue());
				thisClass.objComm.setClubAlbumListRequest("검색어", thisClass.objSearchText.getValue());
				thisClass.objComm.setClubAlbumListRequest("페이지", 1);
				
				thisClass.objClubAlbumListPage.setPage(1);
				thisClass.objClubAlbumList.spinStart();
				thisClass.objComm.getClubAlbumList();
			});
			
			// 삭제버튼 이벤트
			$("div.golf_board  article.btn_area a").click(function(event){
				event.preventDefault();
				
				var $checkbox = thisClass.objClubAlbumList.$getBtnCheckbox();
				var checkData = "";
				
				//vaild check
				if(!thisClass.objRole.isAdmin()){
					return alert('일반회원은 삭제하실 수 없습니다.');
				}else if($checkbox.filter(":checked").length == 0){ 
					return alert("체크된 삭제항목이 없습니다.");
				}
				
				//data set
				$checkbox.filter(":checked").each(function(){
					var n = $checkbox.index($(this));
					if(checkData != "") checkData += ",";
					checkData += thisClass.objClubAlbumList.boardList[n]["게시판키"] ;
				});
				
				thisClass.objComm.deleteClubAlbumList({"게시판키": checkData});				
				
			});
			
		}
		//상세보기
		, goView: function(n){
			if(!this.objRole.isOpenView(this.objClubAlbumList.boardList[n]["공개유무"])){
					alert(this.objRole.getError());
					return;
				}
				document.location.href = "club_picture_view.html?club_seq=" + this.club_seq + "&board_seq="+ this.objClubAlbumList.boardList[n]["게시판키"] + "&club_my=" +(this.club_my? "&club_my=Y":"");
		}
	}
	
	document.objControl = new clsControl();
	document.objControl._init();
});